#招生数据市场统计服务类  flydragon
class StatisticalDatum::RecruitMarketService
  include HeiPisService

  #company 单位
  #studio 分店
  def initialize(company, studio)
    @company = company
    @studio = studio
  end


  #执行方法 返回值
  def call

  	month_begin_at = Date.new(Date.current.year, Date.current.month)

    market_names = Array.new(10,"未知")
    market_values = Array.new(10,0)
  	market_filter_params = {:company_id => @company.id,:start_date => Time.new(month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}
  	market_filter_params[:end_date] = Time.now
    
    market_filter_sql = "employees.company_id = :company_id and (students.created_at between :start_date and :end_date)"
    if @studio.present?
      market_filter_params[:studio_id] = @studio.id 
      market_filter_sql += " and students.studio_id = :studio_id"
    end

    Rails.logger.info "sql ##############数据为:#{ market_filter_sql}"
    Rails.logger.info "params ##############数据为:#{ market_filter_params}"

    #市场
    market_data = Student.joins(:market_employee).select("employees.name as name, count(students.market_employee_id) as value").where(market_filter_sql,market_filter_params).group(:market_employee_id).order("count(students.market_employee_id) desc").limit(10)
   
    market_data.each_with_index do |md,i|
      market_names[10-i] = md["name"]
      market_values[10-i] = md["value"]
    end



    #回访
    revisit_names = Array.new(10,"未知")
    revisit_values = Array.new(10,0)
  	revisit_filter_params = {:company_id => @company.id,:start_date => Time.new(month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}
  	revisit_filter_params[:end_date] = Time.now
    
    revisit_filter_sql = "employees.company_id = :company_id and (student_remarks.created_at between :start_date and :end_date)"
    if @studio.present?
      revisit_filter_params[:studio_id] = @studio.id 
      revisit_filter_sql += " and potential_students.studio_id = :studio_id"
    end

    

    #回访
    revisit_data = StudentRemark.joins(:market_employee,:potential_student).select("employees.name as name, count(student_remarks.market_employee_id) as value").where(revisit_filter_sql,revisit_filter_params).group("student_remarks.market_employee_id").order("count(student_remarks.market_employee_id) desc").limit(10)
    revisit_data.each_with_index do |md,i|
      revisit_names[10-i] = md["name"]
      revisit_values[10-i] = md["value"]
    end
    Result.new(market_names,market_values,revisit_names,revisit_values)
  end

  #内部类,指定结果返回值
  class Result
  	attr_reader :market_names, :market_values,:revisit_names,:revisit_values

	def initialize(market_names, market_values,revisit_names,revisit_values)
      @market_names = market_names
      @market_values = market_values
      @revisit_names = revisit_names
      @revisit_values = revisit_values
    end 

  end

end

